package com.study.talk.common.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.talk.common.exception.BadRequestException;
import com.study.talk.common.resullt.FwResult;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ExceptionHandlerFilter extends OncePerRequestFilter {

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (RuntimeException e) {
            Integer code = (Integer) request.getAttribute("errorCode");
            String errorMsg = (String) request.getAttribute("errorMsg");
            if (code==null){
                code=401;
            }
            if (errorMsg==null){
                errorMsg="认证失败，请重新登录后重试";
            }
            BadRequestException errorResponse = new BadRequestException(code,errorMsg);
            response.setStatus(code);
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(convertObjectToJson(errorResponse));
        }
    }

    public String convertObjectToJson(BadRequestException error) throws JsonProcessingException {
        if (error == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(FwResult.failedMsg(error.getCode(),error.getMessage()));
    }
}